package com.rxy.rabbitmq.quickstart;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
/**
 * 消费者模型构建 
 * @author ruoxiyuan
 *
 */
public class Consumer {

	public static void main(String[] args) throws Exception {
		
		//1 创建一个ConnectionFactory, 并进行配置
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("192.168.43.157");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/");
		
		//2 通过连接工厂创建连接
		Connection connection = connectionFactory.newConnection();
		
		//3 通过connection创建一个Channel
		Channel channel = connection.createChannel();
		
		//4 声明（创建）一个队列
		String queueName = "test001";
		//queueDeclare(queue, durable, exclusive, autoDelete, arguments)
		//queue：队列名称	durable：是否持久化	  exclusive：独占，表示这个队列只有这一个channel能去监听，目的是为了保障顺序消费
		//autoDelete：队列如果与其他的exchange都没有绑定关系，那么会自动进行删除      arguments：扩展参数
		channel.queueDeclare(queueName, true, false, false, null);
		
		//5 创建消费者
		QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
		
		//6 设置Channel
		//basicConsume(String queue, boolean autoAck, Consumer callback)
		//queue：队列名称    autoAck：是否自动签收     callback：消费者
		channel.basicConsume(queueName, true, queueingConsumer);
		
		while(true){
			//7 获取消息
			//nextDelivery不带参数会一直阻塞，待参数表示超时时间，超过指定时间没有接收到消息就放行
			Delivery delivery = queueingConsumer.nextDelivery();
			String msg = new String(delivery.getBody());
			System.err.println("消费端: " + msg);
			//Envelope envelope = delivery.getEnvelope();
		}
		
	}
}
